using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using UwinEducation.Domain.Entities;
using UwinEducation.Domain.IRepositories;
using UwinEducation.Infrastructure.Persistence;
using UwinEducation.Shared.Enums;
using UwinEducation.Shared.Models;

namespace UwinEducation.Infrastructure.Repositories
{
    /// <summary>
    /// 描述管理仓储实现
    /// </summary>
    public class DescriptionRepository : Repository<Description, Guid>, IDescriptionRepository
    {
        private readonly ApplicationDbContext _context;

        public DescriptionRepository(ApplicationDbContext context) : base(context)
        {
            _context = context;
        }

        /// <summary>
        /// 根据类型获取描述列表
        /// </summary>
        public async Task<List<Description>> GetByTypeAsync(DescriptionType type)
        {
            return await _context.Descriptions
                .AsNoTracking()
                .Where(d => d.Type == type)
                .OrderBy(d => d.CreatedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 根据标题模糊查询
        /// </summary>
        public async Task<List<Description>> GetByTitleAsync(string title)
        {
            return await _context.Descriptions
                .AsNoTracking()
                .Where(d => d.Title.Contains(title))
                .OrderByDescending(d => d.CreatedAt)
                .ToListAsync();
        }

        /// <summary>
        /// 分页查询描述
        /// </summary>
        public async Task<PagedResult<Description>> GetPagedAsync(DescriptionPageRequest request)
        {
            var query = _context.Descriptions
                .AsNoTracking()
                .AsQueryable();

            // 应用过滤条件
            if (request.Type.HasValue)
            {
                query = query.Where(d => d.Type == request.Type.Value);
            }

            if (!string.IsNullOrEmpty(request.Title))
            {
                query = query.Where(d => d.Title.Contains(request.Title));
            }

            if (!string.IsNullOrEmpty(request.Content))
            {
                query = query.Where(d => d.Content.Contains(request.Content) || d.EnContent.Contains(request.Content));
            }


            // 计算总数
            var total = await query.CountAsync();

            // 应用分页
            var items = await query
                .OrderByDescending(d => d.CreatedAt)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToListAsync();

            return new PagedResult<Description>
            {
                Total = total,
                Items = items
            };
        }
    }
} 